<script setup>
import FormComponent from "@/components/form/modle/FormComponent.vue";
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router"; // 使用 useRouter 钩子
import axios from "axios";
import {ElMessage} from "element-plus";
let router = useRouter(); // 获取路由实例
let articlesArr = ref([{consultantId: 0}]);
let labArr = ref([
  {"articleId": "文章编号"},
  {"articleTitle": "文章标题"},
  // {"content": "内容"},
  {"publishTime": "发布时间"},
  // { "image": "图片" },
  // { "consultantId": "咨询师编号" }
]);
// function upData(index) {
//   router.push({path: '/Home/articles/editArticles', query: {ArticleContentId: articlesArr.value[index].consultantId}});
// }
function upData(index) {
  router.push({path: '/Home/editArticles', query: {ArticleContentId: articlesArr.value[index].articleId}});
}

let id = 0;
if (localStorage.getItem('key')) {
  id = JSON.parse(localStorage.getItem('key')).data.consultantId
}

function deleteForm(index) {
  console.log("删除" + index);

  // 删除数组中指定元素
  axios.delete("/articles/" + articlesArr.value[index].articleId).then(res => {
    if (res.data.code === 200) {
      ElMessage("删除成功");
      articlesArr.value.splice(index, 1);
    } else {
      ElMessage("删除失败");
    }
  }).catch(err => {
    console.log(err);
  });
}

const insert = () => {
  console.log(1111)
  router.push({
    path: '/Home/editArticles'
  })
}
const articlesDetail = (index) => {
  var articleId = articlesArr.value[index].articleId
  console.log(1111)
  router.push({
    path: '/Home/ArticlesDetail', query: {articleId: articleId}
  })
}
const uploadMyImage = (event, index) => {
  const files = event.target.files;
  if (files.length === 0) {
    console.log('没有文件被选择');
    return;
  }
  const formData = new FormData();
  formData.append('file', files[0]);
  // for (let i = 0; i < files.length; i++) {
  //   formData.append('file', files[i]);
  // }
  axios.post('http://127.0.0.1:9090/course/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => {
    console.log('文件上传成功', response);
    articlesArr.value[index].image = response.data.data;
    axios.put("/articles", articlesArr.value[index]).then(res => {
      if (res.data.code === 200) {
        ElMessage("修改文章封面成功")
        router.push("/home/articles")
      } else {
        ElMessage("修改文章封面失败")
      }
    }).catch(err => {
      console.log(err);
    });
    // 处理成功响应
  })
      .catch(error => {
        console.error('文件上传失败', error);
        // 处理错误响应
      });
}
// 总页数
let total = ref(0);
const currentPage = ref(1);
// 处理分页变化
const handlePageChange = (pageNum) => {
  currentPage.value = pageNum;
  getArticlesArr(pageNum, 3);
};
onMounted(() => {
  getArticlesArr(1, 3)
})
const getArticlesArr = (pageNum, pageSize) => {
  axios.get('/getArticles?pageNum=' + pageNum + '&pageSize=' + pageSize + "&id=" + id,
  ).then((response) => {
    console.log(response.data.list);
    total.value = response.data.total;
    if (response.data.list) {
      articlesArr.value = response.data.list;
    } else {
      articlesArr.value = [];
    }
  }).catch((error) => {
    console.log(error);
  })
}
</script>


<template>
  <div class="articles">
    <button
        style="position: relative;top: 30px;height:25px;font-size: 14px;background-color: rgba(64,158,255,0.81);width: 100px;text-align:  center;cursor:pointer;border-radius: 10px;color: white;border: none;margin-left:20px;float: none"
        @click="insert">发布文章
    </button>
    <FormComponent :label-arr="labArr" :table-data="articlesArr">
      <el-table-column label="文章内容(点击查看详情)" width="270">
        <template v-slot="scope">
          <div @click="articlesDetail(scope.$index)" style="display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;" v-html="articlesArr[scope.$index].content"></div>
        </template>
      </el-table-column>
      <el-table-column label="文章封面(点击图片修改)" width="270">
        <template v-slot="scope">

          <!-- 自定义文件上传按钮  class="custom-file-button"-->
          <label v-if="articlesArr" :for="'fileInput' + scope.$index">
            <img width="100%" :src="'http://127.0.0.1:9090/file/download/byte/' + articlesArr[scope.$index].image"
                 alt="加载失败">
          </label>
          <!-- 原生文件输入框，设置为透明并绝对定位到屏幕外 -->
          <input type="file" @change="uploadMyImage($event, scope.$index)"
                 style="opacity: 0; position: absolute; left: -9999px;" :id="'fileInput' + scope.$index">

          <!--          <img src="" alt="加载失败">-->
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template v-slot="scope">
          <button
              style="height:25px;font-size: 14px;background-color: rgba(64,158,255,0.81);width: 100px;text-align:  center;cursor:pointer;border-radius: 10px;color: white;border: none;float: none"
              @click="deleteForm(scope.$index)">删除
          </button>
          <button
              style="height:25px;font-size: 14px;background-color: rgba(64,158,255,0.81);width: 100px;text-align:  center;cursor:pointer;border-radius: 10px;color: white;border: none;margin-left:20px;float: none"
              @click="upData(scope.$index)">编辑
          </button>
        </template>
      </el-table-column>
    </FormComponent>
    <!-- 分页控制 -->
    <el-pagination
        :current-page="currentPage"
        :page-size="3"
        :total="total"
        @current-change="handlePageChange">
    </el-pagination>
  </div>
</template>

<style scoped>

</style>